<template>
  <div id="app">
    <nav>
      <router-link to="/">首页</router-link> |
      <template v-if="!isAuthenticated">
        <router-link to="/login">登录</router-link> |
        <router-link to="/register">注册</router-link>
      </template>
      <template v-else>
        <router-link to="/article/create">写文章</router-link> |
        <router-link to="/profile">个人信息</router-link> |
        <span>欢迎，{{ username }}</span> |
        <a href="#" @click.prevent="handleLogout">退出</a>
      </template>
    </nav>
    <router-view/>
  </div>
</template>

<script setup>
import { computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { getUserInfo } from './api/user'

const store = useStore()
const router = useRouter()
const isAuthenticated = computed(() => store.state.token)
const username = computed(() => store.state.user?.name || store.state.user?.account)

const handleLogout = () => {
  store.commit('logout')
  router.push('/login')
}

const checkAuth = async () => {
  if (store.state.token) {
    try {
      const response = await getUserInfo(store.state.token)
      if (response.code === 200) {
        store.commit('setUser', response.data)
        if (router.currentRoute.value.path === '/login') {
          router.push('/')
        }
      } else {
        store.commit('logout')
      }
    } catch (error) {
      store.commit('logout')
    }
  }
}

watch(isAuthenticated, (newValue) => {
  if (newValue) {
    router.push('/')
  }
})

onMounted(() => {
  checkAuth()
})
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  background-color: #e3f2fd;
  min-height: 100vh;
}

nav {
  padding: 30px;
  text-align: center;
  background-color: #f8f9fa;
}

nav a {
  font-weight: bold;
  color: #1e88e5;
  text-decoration: none;
  margin: 0 10px;
}

nav a.router-link-exact-active {
  color: #0d47a1;
}
</style> 